<template>
    <n-drawer :show="active" :width="width" :mask-closable="false" @update:show="(flag:boolean) => (active = flag)">
        <n-drawer-content :native-scrollbar="false" title="修改车型" closable>
            <n-space vertical :size="24" v-if="model.id && model.serie.id == '0'">
                <n-form label-placement="left" inline :show-feedback="false">
                    <n-form-item label="品牌">                       
                        <n-select
                            v-if="tree.length > 0"
                            placeholder="请选择品牌"
                            :style="{ width: '200px' }"
                            filterable
                            :options="tree"
                            children-field="corps"
                            value-field="id"
                            label-field="name"
                            clearable
                            @update:value="(value:string)=>{ execLoadSeries(value)}"
                        />
                    </n-form-item>
                    <n-form-item label="车系" v-if="series.length > 0">
                        <n-select v-model:value="setting.sid" :style="{ width: '300px' }" :options="series" label-field="name" value-field="id" />
                    </n-form-item>

                    <n-form-item v-if="series.length > 0">
                        <n-button type="primary" :disabled="!setting.sid" @click="doSetSerie">保存车系</n-button>
                    </n-form-item>
                </n-form>
            </n-space>
            <n-space vertical :size="24" v-if="model.id && model.serie.id != '0'">
                <n-form label-placement="left" inline :show-feedback="false">
                    <n-form-item label="车系编号">
                        <b>{{ car.serie.id }}</b>
                    </n-form-item>
                    <n-form-item label="车牌号码">
                        <b>{{ car.cno }}</b>
                    </n-form-item>
                    <n-form-item label="车架号">
                        <b>{{ car.vin }}</b>
                    </n-form-item>
                    <n-form-item label="发动机号">
                        <b>{{ car.eno }}</b>
                    </n-form-item>
                    <n-form-item label="年款">
                        <b>{{ car.attr.year }} 款</b>
                    </n-form-item>
                </n-form>
                <n-form label-placement="left" :model="model" :rules="rules" ref="formRef" :show-feedback="false">
                    <n-space vertical :size="24">
                        <n-grid :cols="24" :x-gap="24">
                            <n-form-item-gi :span="18" label="车型名称" path="name">
                                <n-input v-model:value="model.name" placeholder="请填写车型名称" maxlength="64" show-count />
                            </n-form-item-gi>
                            <n-form-item-gi :span="6" label="车身颜色" path="color">
                                <n-select v-model:value="model.color" filterable tag placeholder="车身颜色" :options="colorOpts" />
                            </n-form-item-gi>
                        </n-grid>
                        <n-card v-if="serie.id" size="small">
                            <n-collapse :default-expanded-names="defNames">
                                <n-collapse-item :title="`默认图片 共 ${dimgs.length} 张`" name="default">
                                    <n-grid :cols="4" v-if="dimgs.length > 0" :x-gap="12" :y-gap="12">
                                        <n-gi :span="1" v-for="cover in dimgs">
                                            <n-card size="small">
                                                <n-space vertical>
                                                    <n-image :width="width / 4 - 50" :height="((width / 4 - 50) / 5) * 3" object-fit="cover" :src="cover.url" />
                                                    <n-space justify="space-between" :style="{ width: '100%' }" :align="'center'" :wrap="false" inline>
                                                        <n-space size="small">
                                                            <n-text>{{ cover.year }}款</n-text>
                                                            <n-text>{{ cover.color }}</n-text>
                                                            <n-text v-if="serie.prop">{{ cover.type }}</n-text>
                                                        </n-space>
                                                        <n-button
                                                            :type="model.cover == cover.url ? 'info' : 'default'"
                                                            size="tiny"
                                                            @click="
                                                                () => {
                                                                    model.cover = cover.url
                                                                    model.mold = cover.type
                                                                    model.color = cover.color
                                                                }
                                                            "
                                                        >
                                                            {{ model.cover == cover.url ? '已选' : '选择' }}
                                                        </n-button>
                                                    </n-space>
                                                </n-space>
                                            </n-card>
                                        </n-gi>
                                    </n-grid>
                                    <n-empty v-else></n-empty>
                                </n-collapse-item>
                                <n-collapse-item v-for="(covers, year) in yimgs" :title="`${year} 款 共 ${covers.length} 张`" :name="year">
                                    <n-grid :cols="4" v-if="covers.length > 0" :x-gap="12" :y-gap="12">
                                        <n-gi :span="1" v-for="cover in covers">
                                            <n-card size="small">
                                                <n-space vertical>
                                                    <n-image :width="width / 4 - 60" :height="((width / 4 - 60) / 5) * 3" object-fit="cover" :src="cover.url" />
                                                    <n-space justify="space-between" :style="{ width: '100%' }" :align="'center'" :wrap="false" inline>
                                                        <n-space size="small">
                                                            <n-text>{{ cover.year }}款</n-text>
                                                            <n-text>{{ cover.color }}</n-text>
                                                            <n-text v-if="serie.prop">{{ cover.type }}</n-text>
                                                        </n-space>
                                                        <n-button
                                                            :type="model.cover == cover.url ? 'info' : 'default'"
                                                            size="tiny"
                                                            @click="
                                                                () => {
                                                                    model.cover = cover.url
                                                                    model.mold = cover.type
                                                                    model.color = cover.color
                                                                }
                                                            "
                                                        >
                                                            {{ model.cover == cover.url ? '已选' : '选择' }}
                                                        </n-button>
                                                    </n-space>
                                                </n-space>
                                            </n-card>
                                        </n-gi>
                                    </n-grid>
                                    <n-empty v-else></n-empty>
                                </n-collapse-item>
                                <n-collapse-item :title="`未分组图片 共 ${nimgs.length} 张`" name="none" v-if="nimgs.length > 0">
                                    <n-grid :cols="4" :x-gap="12" :y-gap="12">
                                        <n-gi :span="1" v-for="cover in nimgs">
                                            <n-card size="small">
                                                <n-space vertical>
                                                    <n-image :width="width / 4 - 50" :height="((width / 4 - 50) / 5) * 3" object-fit="cover" :src="cover.url" />
                                                    <n-space justify="space-between" :style="{ width: '100%' }" :align="'center'" :wrap="false" inline>
                                                        <n-space size="small">
                                                            <n-text>{{ cover.year }}款</n-text>
                                                            <n-text>{{ cover.color }}</n-text>
                                                            <n-text v-if="serie.prop">{{ cover.type }}</n-text>
                                                        </n-space>
                                                        <n-button
                                                            :type="model.cover == cover.url ? 'info' : 'default'"
                                                            size="tiny"
                                                            @click="
                                                                () => {
                                                                    model.cover = cover.url
                                                                    model.mold = cover.type
                                                                    model.color = cover.color
                                                                }
                                                            "
                                                        >
                                                            {{ model.cover == cover.url ? '已选' : '选择' }}
                                                        </n-button>
                                                    </n-space>
                                                </n-space>
                                            </n-card>
                                        </n-gi>
                                    </n-grid>
                                </n-collapse-item>
                            </n-collapse>
                        </n-card>
                    </n-space>
                </n-form>
            </n-space>

            <template #footer>
                <n-space justify="end">
                    <n-button type="tertiary" :disabled="loading" @click="() => (active = false)">
                        <template #icon>
                            <n-icon :component="CloseRound" />
                        </template>
                        关闭
                    </n-button>

                    <n-button type="primary" :loading="loading" @click="execSave" v-if="model.id && model.serie.id != '0'">
                        <template #icon>
                            <n-icon :component="CheckRound" />
                        </template>
                        提交保存
                    </n-button>
                </n-space>
            </template>
        </n-drawer-content>
    </n-drawer>
</template>

<script lang="ts" setup>
import { computed, ref, onBeforeMount } from 'vue'
import { CloseRound, CheckRound } from '@vicons/material'

import { Http } from '@/libs'
import { useStore } from '@/store'

const store = useStore()
const width = computed(() => Math.max(store.state.browser.innerWidth * 0.4, 960))

const { $notification: notification } = window
const { $dialog: dialog } = window

const loading = ref(false)

const prop = defineProps({
    show: {
        type: Boolean,
        required: true,
    },
    item: {
        type: Object,
        default: {},
    },
})

const emit = defineEmits(['update:show', 'refresh'])

const active = computed({
    get: () => prop.show,
    set: val => emit('update:show', val),
})
const defNames = ref<any[]>(['default'])

const setting = ref<any>({})

const formRef = ref<any>(null)

const model = ref<any>({})

const rules = {
    name: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请填写车型名称',
    },
    color: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请填写车身颜色',
    },
}
const car = ref<any>({})
const execReset = () => {
    Http.post('/ops/biz/car/detail', { id: prop.item.id }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        car.value = resp.data
        model.value = {
            id: resp.data.id,
            serie: resp.data.serie,
            name: resp.data.name,
            color: resp.data.attr.color,
            cover: resp.data.cover,
            mold: resp.data.attr.mold,
        }
        execLoadSerie()
    })
}

const execSave = (e: Event) => {
    e.preventDefault()
    if (!model.value.cover) {
        notification.error({
            duration: 1500,
            title: '请选择车型图片',
        })
        return
    }
    formRef.value.validate((errors: any[]) => {
        if (!errors) {
            loading.value = true
            Http.post('/ops/biz/car/save', model.value).then(resp => {
                if (resp.stat.err > 0) {
                    loading.value = false
                    return
                }
                emit('refresh', {})
                notification.success({
                    duration: 1500,
                    title: '操作成功',
                    content: '您已成功保存车型信息',
                })
                setTimeout(() => {
                    loading.value = false
                    emit('update:show', false)
                }, 200)
            })
        } else {
            let msgs = errors.map(err => err[0].message)
            notification.error({
                duration: 1500,
                title: '请填写完整内容',
                description: '当前表单存在以下问题，请处理后提交',
                content: msgs.join('\n'),
            })
        }
    })
}
const serie = ref<any>({})
const colorOpts = ref<any>([])

const dimgs = ref<any>([])
const yimgs = ref<any>({})
const nimgs = ref<any>({})

const execLoadSerie = () => {
    if (model.value.serie.id == '0') {
        return
    }
    Http.post('/ops/sys/car/model/serie/detail', { id: model.value.serie.id }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        colorOpts.value = resp.data.colors.map((x: any) => {
            return { label: x, value: x }
        })
        let dimg: any = []
        let nimg: any = []
        let yimg: any = {}

        resp.data.yearg.forEach((yg: any) => {
            yimg[`${yg.begin} - ${yg.close}`] = []
        })

        resp.data.covers.forEach((cover: any) => {
            if (cover.default) {
                dimg[dimg.length] = cover
            }
            let flag = false
            resp.data.yearg.forEach((yg: any) => {
                if (!flag && yg.begin <= cover.year && yg.close >= cover.year) {
                    yimg[`${yg.begin} - ${yg.close}`][yimg[`${yg.begin} - ${yg.close}`].length] = cover
                    flag = true
                }
            })
            if (!flag) {
                nimg[nimg.length] = cover
            }
        })
        dimgs.value = dimg
        yimgs.value = yimg
        nimgs.value = nimg

        serie.value = resp.data
    })
}

const tree = ref<any>([])
const execLoadTree = () => {
    Http.post('/ops/sys/car/model/brand', {
        show: false,
    }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        resp.data.items.forEach((e: any) => (e.type = 'group'))
        tree.value = resp.data.items
    })
}
const series = ref<any[]>([])
const execLoadSeries = (bid: any) => {
    series.value = []
    setting.value = {}
    Http.post('/ops/sys/car/model/serie/list', {
        pager: {
            page: 1,
            size: 10000,
            time: 0,
        },
        query: {
            bid: bid,
            rmd: false,
        },
    }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        series.value = resp.data.items
    })
}
const doSetSerie = () => {
    dialog.success({
        title: `提示?`,
        content: `是否设置品牌车系？设置后将无法恢复`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
            execSetSerie(setting.value.sid)
        },
    })
}
const execSetSerie = (sid: any) => {
    Http.post('/ops/biz/car/serie/set', {
        id: model.value.id,
        sid: sid,
    }).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        emit('refresh', {})
        notification.success({
            duration: 1500,
            title: '操作成功',
            content: '您已成功设置品牌车系',
        })
        execReset()
    })
}

onBeforeMount(() => {
    execReset()
    execLoadTree()
})
</script>
